package org.benxiong.iplay.ui.shared;

import java.util.ArrayList;
import java.util.List;

import org.benxiong.iplay.R;
import org.benxiong.iplay.http.request.RequestFactory;
import org.benxiong.iplay.service.CacheService;
import org.benxiong.iplay.ui.support.OnSwipeTouchListener;
import org.benxiong.iplay.util.LogX;
import org.benxiong.iplay.util.ToastUtil;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.Toast;

import com.loopj.android.http.BinaryHttpResponseHandler;

public class ViewSinglePhotoActivity extends Activity {

	private ImageView		imageView;
	private String			url;
	private ProgressDialog	progressDialog;

	Matrix					matrix	= new Matrix();

	private List<String>	urls;
	private int				currentIndex;
	private boolean			singleMode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_view_single_photo);

		LinearLayout layout = (LinearLayout) findViewById(R.id.view_single_photo_layout);

		imageView = new ImageView(this);
		// imageView.setMinScale((float) 0.5);
		// imageView.setMaxScale(3);
		// imageView.setStrict(false);
		LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
		imageView.setLayoutParams(params);

		final ViewSinglePhotoActivity av = this;

		imageView.setOnTouchListener(new OnSwipeTouchListener() {
			public void onSwipeTop() {
				ActionBar ab = av.getActionBar();
				if (ab.isShowing()) {
					ab.hide();
				} else {
					ab.show();
				}
			}

			public void onSwipeRight() {
				av.loadPreviousImage();
			}

			public void onSwipeLeft() {
				av.loadNextImage();
			}

			public void onSwipeBottom() {
				ActionBar ab = av.getActionBar();
				if (ab.isShowing()) {
					av.finish();
				} else {
					ab.show();
				}
			}
		});
		matrix.setTranslate(100, 100);

		layout.addView(imageView);

		Intent intent = this.getIntent();
		this.url = intent.getStringExtra("url");
		String[] urls = intent.getStringArrayExtra("urls");
		if (urls != null && urls.length > 0) {
			singleMode = false;
			this.urls = new ArrayList<String>();
			for (String str : urls) {
				this.urls.add(str);
			}
			currentIndex = intent.getIntExtra("currentIndex", 0);
			this.startMultiplePhotoView();
		} else {
			singleMode = true;
			this.loadImageFromUrl();
		}
	}

	private void startMultiplePhotoView() {
		this.url = this.urls.get(this.currentIndex);
		this.loadImageFromUrl();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.view_single_photo, menu);
		return true;
	}

	private void loadImageFromUrl() {
		final String theUrl = this.url;
		Bitmap cached = CacheService.getBitmapFromCache(theUrl, true);
		if (cached != null) {
			imageView.setImageBitmap(cached);
			imageView.setImageMatrix(matrix);
		} else {
			this.getProgressDialog().show();
			final ProgressDialog pd = this.getProgressDialog();
			RequestFactory.getInstance().getPic(this.url, new BinaryHttpResponseHandler(RequestFactory.allowedImgTypes) {
				@Override
				public void onSuccess(byte[] data) {
					pd.dismiss();
					if (data == null) {
						return;
					}
					Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
					imageView.setImageBitmap(bitmap);
					imageView.setImageMatrix(matrix);
					// save to cache
					CacheService.addBitmapToCache(theUrl, bitmap, true);
				}

				@Override
				public void onFailure(Throwable arg0, byte[] arg1) {
					pd.dismiss();
					ToastUtil.toast(R.string.load_fail);
				}
			});
		}
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case R.id.photo_report:
			ToastUtil.toast("Report");
			break;
		case R.id.photo_next:
			loadNextImage();
			break;
		case R.id.photo_previous:
			loadPreviousImage();
			break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void loadPreviousImage() {
		if (this.setCurrentIndex(-1)) {
			this.loadImageFromUrl();
		} else {
			ToastUtil.toast("First photo already");
		}
	}

	private void loadNextImage() {
		if (this.setCurrentIndex(1)) {
			this.loadImageFromUrl();
		} else {
			ToastUtil.toast("Last photo already");
		}
	}

	private boolean setCurrentIndex(int increment) {
		if (this.currentIndex + increment > this.urls.size() - 1) {
			this.currentIndex = this.urls.size() - 1;
			return false;
		} else if (this.currentIndex + increment < 0) {
			this.currentIndex = 0;
			return false;
		}
		this.currentIndex = this.currentIndex + increment;
		this.url = this.urls.get(this.currentIndex);
		LogX.print("current index: " + this.currentIndex);
		return true;
	}

	public ProgressDialog getProgressDialog() {
		if (this.progressDialog == null) {
			this.progressDialog = new ProgressDialog(this, ProgressDialog.STYLE_SPINNER);
		}
		return progressDialog;
	}

}
